package com.fresh.controller;

import com.fresh.common.ResponseResult;
import com.github.pagehelper.PageInfo;
import com.fresh.entity.ProIn;
import com.fresh.entity.ProInQO;
import com.fresh.entity.RejIn;
import com.fresh.feignclient.CiPinFeignClient;
import com.fresh.feignclient.LingLiaoFeignClient;
import com.fresh.service.ChengPinService;
import com.fresh.util.SnowflakeIdWorker;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/chengpin")
public class ChengPinController {
    @Autowired
    SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    ChengPinService chengPinService;
    @Autowired
    LingLiaoFeignClient lingLiaoFeignClient;
    @Autowired
    CiPinFeignClient ciPinFeignClient;

    @GetMapping({"/list/{pageNum}"})
    public Object list(ProInQO proInQO, @PathVariable(required = false) Integer pageNum) {
        if (pageNum == null) {
            pageNum = 1;
        }
        PageInfo<ProIn> pageInfo = chengPinService.findPageInfoByCondition(proInQO, pageNum, 3);
        return new ResponseResult(200, "success", pageInfo);

    }

    @PostMapping("/add")
    public Object add(@RequestBody ProIn proIn) {
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String data = sdf.format(dt);

        proIn.setProId(snowflakeIdWorker.nextId());
        proIn.setProIn(data);
        chengPinService.add(proIn);
        return new ResponseResult(200, "success", null);
    }

    //    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(name = "fsp-create-update", rollbackFor = Exception.class)
    @PostMapping("/update")
    public Object update(@RequestBody ProIn proIn) {
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String data = sdf.format(dt);

        proIn.setProEnd(data);
        chengPinService.update(proIn);
        //次品添加
        RejIn rejIn = new RejIn();
        rejIn.setRoNo(proIn.getRoNo());
        rejIn.setCgNo(proIn.getCgNo());
        rejIn.setRiName(proIn.getRiName());
        rejIn.setCgGname(proIn.getCgGname());
        rejIn.setRejNum(proIn.getRoNum() - proIn.getProNum());
        rejIn.setRejUname(proIn.getProUname());
        ciPinFeignClient.add(rejIn);
        return lingLiaoFeignClient.update(proIn.getRoNo());
    }

    @PostMapping("/updatePro")
    public Object updatePro(@RequestBody ProIn proIn) {
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String data = sdf.format(dt);
        proIn.setProEnd(data);
        chengPinService.updatePro(proIn);
        return new ResponseResult(200, "success", null);
    }
}
